package com.cskaoyan.mall.controller.admin;

import com.cskaoyan.mall.model.user.UserVOAndUserSignUpBO;
import com.cskaoyan.mall.service.UserServiceImpl;
import com.cskaoyan.mall.service.UserService;
import com.cskaoyan.mall.util.Result;
import com.google.gson.Gson;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * @author: jyf2000jyf
 */
@WebServlet("/api/admin/user/*")
public class UserServlet extends HttpServlet {
    private UserService userService = new UserServiceImpl();
    private Gson gson = new Gson();

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String requestURI = request.getRequestURI();
        String op = requestURI.replace("/api/admin/user/", "");
        if ("allUser".equals(op)) {
            getAllUser(request, response);
        }
        if ("deleteUser".equals(op)) {
            deleteUser(request, response);
        }
        if ("searchUser".equals(op)) {
            searchUser(request,response);
        }
    }

    private void getAllUser(HttpServletRequest request, HttpServletResponse response) throws IOException {
        Result result = new Result(0, null, userService.getAllUser());
        response.getWriter().println(gson.toJson(result));
    }

    private void deleteUser(HttpServletRequest request, HttpServletResponse response) throws IOException {
        int id = Integer.parseInt(request.getParameter("id"));
        boolean status = userService.deleteUser(id);
        Result result;
        if (status) {
            result = new Result(0, "删除成功", null);
        } else {
            result = new Result(10000, "删除失败", null);
        }
        response.getWriter().println(gson.toJson(result));
    }

    private void searchUser(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String word = request.getParameter("word");
        List<UserVOAndUserSignUpBO> userList = userService.getSearchUser(word);
        Result result = new Result(0,"null",userList);
        response.getWriter().println(gson.toJson(result));
    }
}
